#include <QTableWidget>
#include <QVBoxLayout>
#include <QDebug>

#include "paramswindow.h"
#include "../database/databasemanager.h"

namespace Jcr
{
class ParamsWindowPrivate
{
public:
    ParamsWindowPrivate(ParamsWindow* q);
    ParamsWindow* q_ptr;
    QTableWidget* tableWidget;
    QList<std::string> params;
};

static const int ParamsCount = 29;

ParamsWindowPrivate::ParamsWindowPrivate(ParamsWindow *q) : q_ptr(q)
{
    tableWidget = new QTableWidget(q);
    tableWidget->setColumnCount(2);
    tableWidget->setHorizontalHeaderLabels(QStringList() << QObject::tr("Name") << QObject::tr("Value"));
    QVBoxLayout* layout = new QVBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(tableWidget);
    q->setLayout(layout);
}

ParamsWindow::ParamsWindow(QWidget* parent) : ModelWindow(parent)
{
    d_ptr = new ParamsWindowPrivate(this);
}

ParamsWindow::~ParamsWindow()
{
    delete d_ptr;
}

void ParamsWindow::exec()
{
    QStringList params;
    int rowCount = d_ptr->tableWidget->rowCount();
    if (rowCount < ParamsCount) {
        qDebug() << "Invalid parameters, quit.";
        return;
    }

    for (int i = 0; i < ParamsCount; ++i)
        params << d_ptr->tableWidget->item(i, 1)->text();
    Jcr::DatabaseManager::instance()->addModelParams(this->modelName(), params);
}

void ParamsWindow::setParameters(const QList<std::string>& params)
{
    if (params.isEmpty() && d_ptr->tableWidget->rowCount() != 0) {
        int rowCount = d_ptr->tableWidget->rowCount() > ParamsCount ? ParamsCount : d_ptr->tableWidget->rowCount();
        for (int i = 0; i < rowCount; ++i)
            d_ptr->tableWidget->item(i, 1)->setText("N/A");
    }

    if (params != d_ptr->params) {
        d_ptr->params = params;

        int rowCount = params.size() / 2 + 1;
        d_ptr->tableWidget->setRowCount(rowCount);
        int rowIndex = 0;
        int itemIndex = 0;
        foreach (auto param, params) {
            if (++itemIndex % 2 == 0) {
                QTableWidgetItem* valueItem = new QTableWidgetItem;
                valueItem->setText(param.c_str());
                d_ptr->tableWidget->setItem(rowIndex, 1, valueItem);
                ++rowIndex;
            } else {
                QTableWidgetItem* nameItem = new QTableWidgetItem();
                nameItem->setText(param.c_str());
                d_ptr->tableWidget->setItem(rowIndex, 0, nameItem);
            }
        }
    }
}


} // namespace jcr
